// Project name:JavaRedis
// Creator:muhong
// Date time:2022/12/17,12:39 下午
// Name:DefaultEventExecutorChooser

package org.gmh.util.concurrent;

import java.util.concurrent.atomic.AtomicInteger;

public class DefaultEventExecutorChooserFactory implements EventExecutorChooserFactory {

    public static final DefaultEventExecutorChooserFactory INSTANCE = new DefaultEventExecutorChooserFactory();

    @Override
    public EventExecutorChooser newChooser(EventExecutor[] executors) {
        return new GenericEventExecutorChooser(executors);
    }

    // 轮询的EventLoop选择器
    private static final class GenericEventExecutorChooser implements EventExecutorChooser {

        private final AtomicInteger idx = new AtomicInteger();
        private final EventExecutor[] executors;

        public GenericEventExecutorChooser(EventExecutor[] executors) {
            this.executors = executors;
        }

        @Override
        public EventExecutor next() {
            return executors[Math.abs(idx.getAndIncrement() % executors.length)];
        }
    }
}
